package service

import (
	"errors"
	"math/rand"
	"strconv"
	"strings"
	"time"
	"vrcm/src/vrcm/app/admin/models/monitor"
	dto "vrcm/src/vrcm/app/admin/service/dto/monitor"
	vrpmDto "vrcm/src/vrcm/app/admin/service/dto/vrpm"
	vrpmService "vrcm/src/vrcm/app/admin/service/vrpm"
	"vrcm/src/vrcm/common/apis"
	cDto "vrcm/src/vrcm/common/dto"
	"vrcm/src/vrcm/common/service"
)

type MonitorEvent struct {
	service.Service
}

// GetPage MonitorEvent
func (e *MonitorEvent) GetPage(c *dto.MonitorEventGetPageReq, list *[]monitor.MonitorEvent, count *int64) error {
	var err error
	var data monitor.MonitorEvent

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Order("CASE WHEN task_state = 1 THEN 0 ELSE 1 END, task_state,update_time desc").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("GetPage error:%s \r\n", err)
		return err
	}
	//configIds := make([]int, 0, 5)
	//for _, v := range *list {
	//	v := v
	//	configIds = append(configIds, v.Id)
	//}
	//configs := make([]monitor.MonitorConfig, 0, 5)
	//err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id in ?", configIds).Find(&configs).Error
	//if err != nil {
	//	e.Log.Errorf("get MonitorConfig error:%s \r\n", err)
	//	return err
	//}
	//
	//configMap := make(map[int64][]monitor.MonitorConfig)
	//for _, v := range configs {
	//	v := v
	//	t, ok := configMap[v.BasicId]
	//	if !ok {
	//		t = make([]monitor.MonitorConfig, 0, 5)
	//	}
	//	t = append(t, v)
	//	configMap[v.BasicId] = t
	//}
	//for k, v := range *list {
	//	v := v
	//	configs := configMap[int64(v.Id)]
	//	*(&(*list)[k].MonitorConfigs) = configs
	//}
	return nil
}

// Get 获取MonitorEvent对象
func (e *MonitorEvent) Get(d *dto.MonitorEventGetReq) (*monitor.MonitorEvent, error) {
	var model monitor.MonitorEvent
	err := e.Orm.Model(&model).Where("id=?", d.Id).Find(&model).Error
	if err != nil {
		e.Log.Errorf("get error:%s", err)
		return &model, err
	}

	monitorBasic := MonitorBasic{}
	monitorBasic.Log = e.Log
	monitorBasic.Orm = e.Orm
	basics := make([]monitor.MonitorBasic, 0, 5)
	sId := strconv.Itoa(d.Id)
	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("bind_id=?", sId).Find(&basics).Error
	if err != nil {
		e.Log.Errorf("get error:%s", err)
		return &model, err
	}
	basicsIds := make([]int, 0, 4)
	for _, v := range basics {
		basicsIds = append(basicsIds, v.Id)
	}
	configs := make([]monitor.MonitorConfig, 0, 5)
	err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id in ?", basicsIds).Find(&configs).Error
	if err != nil {
		e.Log.Errorf("get error:%s", err)
		return &model, err
	}

	monitorModels := make([]monitor.MonitorModel, 0, 5)
	for _, v := range basics {
		v := v
		monitorModel := monitor.MonitorModel{}
		monitorModel.MonitorBasic = v
		for _, c := range configs {
			c := c
			if c.BasicId == int64(v.Id) {
				monitorModel.MonitorConfigs = append(monitorModel.MonitorConfigs, c)
			}
		}
		monitorModels = append(monitorModels, monitorModel)
	}
	model.MonitorModels = monitorModels
	if len(monitorModels) > 0 {
		model.MonitorUrl = monitorModels[0].MonitorBasic.MonitorUrl
	}
	return &model, nil
}

func (e *MonitorEvent) Insert(c *dto.MonitorEventInsertReq) error {
	var err error
	var data monitor.MonitorEvent
	now := time.Now().Unix()
	data.TenantId = c.TenantId
	data.EventName = c.EventName
	data.SetId = c.SetId
	data.Password = c.Password
	data.AuditPassword = c.AuditPassword
	data.TaskState = 0
	data.StartTime = c.StartTime
	data.EndTime = c.EndTime
	data.CreateTime = now
	data.UpdateTime = now
	data.Active = 0

	vrpmService := vrpmService.VrcService{}
	vrpmService.Log = e.Log
	number := strconv.Itoa(int(time.Now().Unix()))
	res, err := vrpmService.CreateChannel(&vrpmDto.CreateChannelReq{TenantId: c.TenantId, Name: data.EventName + strconv.Itoa(int(time.Now().Unix())), ChannelNumber: number})
	if err != nil {
		e.Log.Errorf("创建频道失败:%s \r\n", err)
		return err
	}
	if res != nil {
		data.ChannelId = res.Id
		data.GroupId = res.GroupId
		data.SourcePackId = res.SourcePackId
		data.VersionId = res.VersionId
	}
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("创建活动失败:%s \r\n", err)
		return err
	}
	c.Id = data.Id
	return nil
}

func (e *MonitorEvent) Update(c *dto.MonitorEventUpdateReq) error {

	var err error
	var data monitor.MonitorEvent

	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", c.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent:%s \r\n", err)
		return err
	}
	now := time.Now().Unix()
	data.TenantId = c.TenantId
	data.EventName = c.EventName
	data.SetId = c.SetId
	data.Password = c.Password
	data.AuditPassword = c.AuditPassword
	data.StartTime = c.StartTime
	data.EndTime = c.EndTime
	data.UpdateTime = now
	err = e.Orm.Save(&data).Error
	if err != nil {
		e.Log.Errorf("更新活动失败:%s \r\n", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) Remove(d *dto.MonitorEventDeleteReq) error {

	vrpmService := vrpmService.VrcService{}
	vrpmService.Log = e.Log

	//获取活动
	event := monitor.MonitorEvent{}
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id = ?", d.Id).Find(&event).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent error:%s \r\n", err)
		return err
	}

	//获取活动下面的所有监看
	basics := make([]monitor.MonitorBasic, 0, 5)
	sId := strconv.Itoa(d.Id)
	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("bind_id = ?", sId).Find(&basics).Error
	if err != nil {
		e.Log.Errorf("get MonitorBasic error:%s \r\n", err)
		return err
	}

	basicIds := make([]int, 0, 5)
	for _, v := range basics {
		basicIds = append(basicIds, v.Id)
	}

	//获取活动下所有的播放地址记录
	eps := make([]monitor.EventPlayAddress, 0, 5)
	err = e.Orm.Model(&monitor.EventPlayAddress{}).Where("event_id = ?", d.Id).Find(&eps).Error
	if err != nil {
		e.Log.Errorf("get EventPlayAddress error:%s \r\n", err)
		return err
	}

	if event.ChannelId > 0 {
		//删除频道
		err = vrpmService.DeleteChannel(&vrpmDto.DeleteChannelReq{TenantId: event.TenantId, Id: event.ChannelId})
		if err != nil {
			e.Log.Errorf("DeleteChannel error:%s ", err)
			return err
		}
		//删除分组
		err = vrpmService.DeleteGroup(&vrpmDto.DeleteGroupReq{TenantId: event.TenantId, Id: event.ChannelId})
		if err != nil {
			e.Log.Errorf("DeleteGroup error:%s ", err)
			return err
		}
		//删除资源包
		err = vrpmService.DeleteSourcePack(&vrpmDto.DeleteSourcePack{TenantId: event.TenantId, Id: event.ChannelId})
		if err != nil {
			e.Log.Errorf("DeleteSourcePack error:%s ", err)
			return err
		}
	}

	//删除所有的播放地址
	//for _, v := range eps {
	//	v := v
	//	err = vrpmService.DeletePlayAddress(&vrpmDto.DeletePlayAddressReq{TenantId: v.TenantId, ChannelId: event.ChannelId, Id: v.PlayAddressId})
	//	if err != nil {
	//		e.Log.Errorf("DeletePlayAddress error:%s ", err)
	//		return err
	//	}
	//}

	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id = ?", d.Id).Delete(&monitor.MonitorEvent{}).Error
	if err != nil {
		e.Log.Errorf("删除活动失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("bind_id = ?", d.Id).Delete(&monitor.MonitorBasic{}).Error
	if err != nil {
		e.Log.Errorf("删除活动监看失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id in ?", basicIds).Delete(&monitor.MonitorConfig{}).Error
	if err != nil {
		e.Log.Errorf("删除播放地址失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.EventPlayAddress{}).Where("event_id = ?", d.Id).Delete(&monitor.EventPlayAddress{}).Error
	if err != nil {
		e.Log.Errorf("删除播放地址失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id = ?", d.Id).Delete(&monitor.WorksiteNotice{}).Error
	if err != nil {
		e.Log.Errorf("删除活动的工口消息失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.ProgramOrigin{}).Where("event_id = ?", d.Id).Delete(&monitor.ProgramOrigin{}).Error
	if err != nil {
		e.Log.Errorf("删除活动的原始节目单失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.ProgramRound{}).Where("event_id = ?", d.Id).Delete(&monitor.ProgramRound{}).Error
	if err != nil {
		e.Log.Errorf("删除活动的场次节目单失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.WorksiteNoticeHistory{}).Where("event_id = ?", d.Id).Delete(&monitor.WorksiteNoticeHistory{}).Error
	if err != nil {
		e.Log.Errorf("删除活动的工口历史消息失败:%s \r\n", err)
		return err
	}
	err = e.Orm.Model(&monitor.EventMember{}).Where("event_id = ?", d.Id).Delete(&monitor.EventMember{}).Error
	if err != nil {
		e.Log.Errorf("删除活动成员失败:%s \r\n", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) SaveProgram(c *vrpmDto.SaveProgramReq) (int, error) {
	var err error

	//获取活动信息
	var event monitor.MonitorEvent
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("channel_id=?", c.ChannelId).Find(&event).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent error :%s \r\n", err)
		return 0, err
	}

	vrpmService := vrpmService.VrcService{}
	vrpmService.Log = e.Log
	c.VersionId = event.VersionId
	errcode, err := vrpmService.SaveProgram(c)
	if err != nil {
		e.Log.Errorf("保存节目单失败:%s \r\n", err)
		return errcode, err
	}

	if c.Tag != 1 {
		//先删除原来的节目单
		err = e.Orm.Model(&monitor.ProgramOrigin{}).Where("event_id=?", event.Id).Delete(&monitor.ProgramOrigin{}).Error
		if err != nil {
			e.Log.Errorf("delete ProgramOrigin error :%s \r\n", err)
			return errcode, err
		}

		if c.SaveType == 1 {
			err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=?", event.Id).Delete(&monitor.WorksiteNotice{}).Error
			if err != nil {
				e.Log.Errorf("delete WorksiteNotice error :%s \r\n", err)
				return errcode, err
			}
		}

		origins := make([]monitor.ProgramOrigin, 0, 5)
		now := time.Now().Unix()
		for _, v := range c.Epgs {
			origin := monitor.ProgramOrigin{}
			origin.ProgramId = v.ProgramId
			origin.TenantId = event.TenantId
			origin.EventId = event.Id
			origin.ChannelId = event.ChannelId
			origin.IsSkip = 2
			origin.IsPlaying = 2
			origin.ProgramName = v.ProgramName
			origin.Describe = v.Describe
			origin.StartTime = v.StartTime
			origin.EndTime = v.EndTime
			origin.LookUp = v.LookUp
			origin.DelayType = v.DelayType
			origin.DelaySecond = v.DelaySecond
			origin.CreateTime = now
			origin.UpdateTime = now
			origins = append(origins, origin)
		}
		if len(origins) > 0 {
			err = e.Orm.Model(&monitor.ProgramOrigin{}).Create(&origins).Error
			if err != nil {
				e.Log.Errorf("create ProgramOrigin error :%s \r\n", err)
				return errcode, err
			}
		}
	}
	return errcode, nil
}

func (e *MonitorEvent) GetProgramOrigin(c *vrpmDto.GetProgramReq) ([]monitor.ProgramOrigin, error) {
	var err error

	origins := make([]monitor.ProgramOrigin, 0, 3)
	err = e.Orm.Model(&monitor.ProgramOrigin{}).Where("channel_id = ?", c.ChannelId).Find(&origins).Error
	if err != nil {
		e.Log.Errorf("get GetChannelProgram error :%s \r\n", err)
		return origins, err
	}
	return origins, nil
}

func (e *MonitorEvent) GetProgram(c *vrpmDto.GetProgramReq) (map[string][]vrpmDto.EpgRes, error) {
	var err error
	//获取活动
	event := monitor.MonitorEvent{}
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("channel_id = ?", c.ChannelId).Find(&event).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent error:%s \r\n", err)
		return nil, err
	}
	c.VersionId = event.VersionId
	vrpmService := vrpmService.VrcService{}
	vrpmService.Log = e.Log
	res, err := vrpmService.GetProgram(c)
	if err != nil {
		e.Log.Errorf("获取节目单失败:%s \r\n", err)
		return res, err
	}
	paramIdMap := make(map[string]struct{})
	if len(event.SkipParamIds) > 0 {
		arr := strings.Split(event.SkipParamIds, ",")
		for _, v := range arr {
			v := v
			paramIdMap[v] = struct{}{}
		}
	}
	worksiteNotices := make([]monitor.WorksiteNotice, 0, 3)
	err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=?", event.Id).Find(&worksiteNotices).Error
	if err != nil {
		e.Log.Errorf("获取工口消息失败:%s \r\n", err)
		return res, err
	}

	taiBens := make([]monitor.TaiBen, 0, 3)
	err = e.Orm.Model(&monitor.TaiBen{}).Where("event_id=?", event.Id).Find(&taiBens).Error
	if err != nil {
		e.Log.Errorf("获取台本消息失败:%s \r\n", err)
		return res, err
	}
	worksiteNoticeMap := make(map[string][]monitor.WorksiteNotice)
	for _, notice := range worksiteNotices {
		notice := notice
		notices, ok := worksiteNoticeMap[notice.ProgramId]
		if !ok {
			notices = make([]monitor.WorksiteNotice, 0, 5)
		}
		notices = append(notices, notice)
		worksiteNoticeMap[notice.ProgramId] = notices
	}

	taiBenMap := make(map[string][]monitor.TaiBen)
	for _, taiBen := range taiBens {
		taiBen := taiBen
		taiBens, ok := taiBenMap[taiBen.ProgramId]
		if !ok {
			taiBens = make([]monitor.TaiBen, 0, 5)
		}
		taiBens = append(taiBens, taiBen)
		taiBenMap[taiBen.ProgramId] = taiBens
	}

	active := strconv.Itoa(event.Active)
	for _, programs := range res {
		for k, program := range programs {
			*(&programs[k].WorksiteNotices) = make([]monitor.WorksiteNotice, 0, 5)
			if program.ProgramId == active {
				*(&programs[k].IsPlaying) = 1
			} else {
				*(&programs[k].IsPlaying) = 2
			}
			_, ok := paramIdMap[program.ProgramId]
			if !ok {
				*(&programs[k].IsSkip) = 2
			} else {
				*(&programs[k].IsSkip) = 1
			}

			notices, ok := worksiteNoticeMap[program.ProgramId]
			if ok {
				*(&programs[k].WorksiteNotices) = notices
			}
			*(&programs[k].TaiBens) = make([]monitor.TaiBen, 0, 5)
			taiBens, ok := taiBenMap[program.ProgramId]
			if ok {
				*(&programs[k].TaiBens) = taiBens
			}
		}

	}
	return res, nil
}

func (e *MonitorEvent) UpdateProgramIndex(c *vrpmDto.UpdateProgramIndexReq) error {

	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", c.Id).Update("active", c.Active).Error
	if err != nil {
		e.Log.Errorf("更新节目单索引失败:%s \r\n", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) SaveProgramRound(c *vrpmDto.SaveProgramReq) ([]monitor.ProgramOrigin, error) {

	origins := make([]monitor.ProgramOrigin, 0, 5)
	//获取最大场次
	var maxRound int64
	if len(c.Epgs) > 0 {
		err := e.Orm.Model(&monitor.ProgramRound{}).Select("COALESCE(MAX(program_round), 0)").Where("event_id=?", c.Epgs[0].EventId).Find(&maxRound).Error
		if err != nil {
			e.Log.Errorf("get ProgramRound:%s \r\n", err)
			return origins, err
		}
		//重制节目单
		param := make(map[string]interface{})
		param["active"] = 0
		param["skip_param_ids"] = ""
		err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", c.Epgs[0].EventId).Updates(&param).Error
		if err != nil {
			e.Log.Errorf("update MonitorEvent:%s \r\n", err)
			return origins, err
		}

		//获取原始节目单
		err = e.Orm.Model(&monitor.ProgramOrigin{}).Where("event_id=?", c.Epgs[0].EventId).Find(&origins).Error
		if err != nil {
			e.Log.Errorf("get ProgramOrigin error:%s ", err)
			return origins, err
		}
	} else {
		//获取原始节目单
		err := e.Orm.Model(&monitor.ProgramOrigin{}).Where("event_id=?", c.EventId).Find(&origins).Error
		if err != nil {
			e.Log.Errorf("get ProgramOrigin error:%s ", err)
			return origins, err
		}
		return origins, err
	}

	now := time.Now().Unix()
	epgs := make([]monitor.ProgramRound, 0, 5)
	for _, v := range c.Epgs {
		model := monitor.ProgramRound{}
		model.Id = v.Id
		model.ProgramId = v.ProgramId
		model.TenantId = v.TenantId
		model.ChannelId = v.ChannelId
		model.EventId = v.EventId
		model.ChannelId = v.ChannelId
		model.StartTime = v.StartTime
		model.EndTime = v.EndTime
		model.ProgramName = v.ProgramName
		model.Describe = v.Describe
		model.IsSkip = v.IsSkip
		model.DelayType = v.DelayType
		model.DelaySecond = v.DelaySecond
		if v.Id <= 0 {
			model.CreateTime = now
			model.UpdateTime = now
		} else {
			model.UpdateTime = now
		}
		model.ProgramRound = int(maxRound) + 1
		epgs = append(epgs, model)
	}

	if len(epgs) > 0 {
		err := e.Orm.Save(&epgs).Error
		if err != nil {
			e.Log.Errorf("SaveProgramRound error:%s ", err)
			return origins, err
		}
	}

	return origins, nil
}

func (e *MonitorEvent) SaveEventMonitor(c *dto.MonitorBasicUpdateReq) error {

	vrpmService := vrpmService.VrcService{}
	vrpmService.Log = e.Log
	var err error
	var data = monitor.MonitorBasic{}
	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("id=?", c.MonitorBasic.Id).Find(&data).Error
	if err != nil {
		e.Log.Errorf("get MonitorBasic:%s \r\n", err)
		return err
	}

	var eventMonitor monitor.MonitorEvent
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", c.BindId).Find(&eventMonitor).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent:%s \r\n", err)
		return err
	}
	//如果是修改模版则需要把原来的视窗配置删除
	if data.Id > 0 && data.TemplateType != c.MonitorBasic.TemplateType {
		err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id=?", data.Id).Delete(&monitor.MonitorConfig{}).Error
		if err != nil {
			e.Log.Errorf("delete MonitorConfig:%s ", err)
			return err
		}
	}

	if len(c.Configs) > 0 {
		data.MonitorUrl = c.Configs[0].StreamUrl
	}
	c.Generate(&data)
	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("Save  MonitorBasic error:%s ", err)
		return err
	}

	now := time.Now().Unix()
	if len(c.Configs) > 0 {
		for k, v := range c.Configs {
			v := v
			if v.Id <= 0 {
				*(&c.Configs[k].CreateTime) = now
			} else {
				*(&c.Configs[k].UpdateTime) = now
			}
			*(&c.Configs[k].BasicId) = int64(data.Id)
		}
		err = e.Orm.Save(&c.Configs).Error
		if err != nil {
			e.Log.Errorf("save MonitorConfig:%s ", err)
			return err
		}
	}

	//新增播放数据
	if c.MonitorBasic.Id <= 0 {
		res, err := vrpmService.CreatePlayAddress(&vrpmDto.CreatePlayAddressReq{TenantId: data.TenantId, Name: "WebRTC", ChannelId: eventMonitor.ChannelId, AutoPlayUrl: data.MonitorUrl, BitrateMultipleEnable: 1, IsForce: 1, VersionId: eventMonitor.VersionId})
		if err != nil {
			e.Log.Errorf("CreatePlayAddress error:%s ", err)
			return err
		}
		if res != nil {
			ep := monitor.EventPlayAddress{MonitorId: data.Id, EventId: eventMonitor.Id, PlayAddressId: res.Id, TenantId: data.TenantId}
			err = e.Orm.Save(&ep).Error
			if err != nil {
				e.Log.Errorf("save EventPlayAddress:%s ", err)
				return err
			}
		}

	}
	c.MonitorBasic.Id = data.Id

	return nil
}

func (e *MonitorEvent) RemoveEventMonitor(d *dto.EventMonitorDeleteReq) error {

	vrpmService := vrpmService.VrcService{}
	vrpmService.Log = e.Log
	basic := monitor.MonitorBasic{}
	err := e.Orm.Model(&monitor.MonitorBasic{}).Where("id =  ?", d.Id).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("获取监看任务失败: %s", err)
		return err
	}

	if basic.MonitorState == 1 {
		return errors.New("监看任务已启用！")
	}

	eventMonitor := &monitor.MonitorEvent{}
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id = ?", basic.BindId).Find(&eventMonitor).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent: %s", err)
		return err
	}

	ep := monitor.EventPlayAddress{}
	err = e.Orm.Model(&monitor.EventPlayAddress{}).Where("event_id=? and monitor_id=?", eventMonitor.Id, basic.Id).Find(&ep).Error
	if err != nil {
		e.Log.Errorf("get EventPlayAddress: %s", err)
		return err
	}

	err = vrpmService.DeletePlayAddress(&vrpmDto.DeletePlayAddressReq{TenantId: basic.TenantId, ChannelId: eventMonitor.ChannelId, Id: ep.PlayAddressId, VersionId: eventMonitor.VersionId})
	if err != nil {
		e.Log.Errorf("DeletePlayAddress error:%s ", err)
		return err
	}

	err = e.Orm.Model(&monitor.EventPlayAddress{}).Where("event_id=? and monitor_id=? and play_address_id=?", eventMonitor.Id, basic.Id, ep.PlayAddressId).Delete(&monitor.EventPlayAddress{}).Error
	if err != nil {
		e.Log.Errorf("delete EventPlayAddress: %s", err)
		return err
	}

	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("id =?", d.Id).Delete(&monitor.MonitorBasic{}).Error
	if err != nil {
		e.Log.Errorf("删除监看任务失败: %s", err)
		return err
	}
	err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id = ?", d.Id).Delete(&monitor.MonitorConfig{}).Error
	if err != nil {
		e.Log.Errorf("删除监看详情失败: %s", err)
		return err
	}

	return nil
}

func (e *MonitorEvent) StartEventMonitor(d *dto.StartMonitorEventReq) error {

	events := make([]monitor.MonitorEvent, 0, 5)
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id !=? and task_state=1", d.Id).Find(&events).Error
	if err != nil {
		e.Log.Errorf("start MonitorEvent error:%s ", err)
		return err
	}
	if len(events) > 0 {
		return errors.New(string(apis.EventStartedError.Code))
	}

	param := make(map[string]interface{})
	param["task_state"] = 1
	param["start_time"] = time.Now().Unix()
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", d.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("start MonitorEvent error:%s ", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) StopEventMonitor(d *dto.StopMonitorEventReq) error {
	param := make(map[string]interface{})
	param["task_state"] = 2
	param["monitor_state"] = 2
	param["end_time"] = time.Now().Unix()
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", d.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("stop MonitorEvent error:%s ", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) StartMonitor(d *dto.StartMonitorReq) error {
	err := e.Orm.Model(&monitor.MonitorBasic{}).Where("id=?", d.Id).Update("monitor_state", 1).Error
	if err != nil {
		e.Log.Errorf("start StartMonitor error:%s ", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) DeleteMonitor(d *dto.DeleteMonitorReq) error {
	err := e.Orm.Model(&monitor.MonitorBasic{}).Where("id=?", d.Id).Delete(&monitor.MonitorBasic{}).Error
	if err != nil {
		e.Log.Errorf("delete StartMonitor error:%s ", err)
		return err
	}
	err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id=?", d.Id).Delete(&monitor.MonitorConfig{}).Error
	if err != nil {
		e.Log.Errorf("delete MonitorConfig error:%s ", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) StopMonitor(d *dto.StopMonitorReq) error {
	err := e.Orm.Model(&monitor.MonitorBasic{}).Where("id=?", d.Id).Update("monitor_state", 2).Error
	if err != nil {
		e.Log.Errorf("stop StopMonitor error:%s ", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) EnableMonitor(d *dto.EnableMonitorReq) error {
	sId := strconv.Itoa(d.Id)
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", sId).Update("monitor_state", d.MonitorState).Error
	if err != nil {
		e.Log.Errorf("EnableMonitor error:%s ", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) SkipProgram(c *vrpmDto.SkipProgramReq) error {
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", c.Id).Update("skip_param_ids", c.ParamIds).Error
	if err != nil {
		e.Log.Errorf("更新跳过节目单失败:%s \r\n", err)
		return err
	}

	return nil
}

// GetProgramPage MonitorEvent
func (e *MonitorEvent) GetProgramPage(c *dto.ProgramGetPageReq, list *[]monitor.ProgramRoundModel, count *int64) error {
	var err error
	var data monitor.ProgramRound

	//SELECT program_round, MIN(start_time) AS start_time, MAX(end_time) AS end_time
	//FROM program_round
	//GROUP BY program_round;
	err = e.Orm.Model(&data).Select("program_round, event_id,MIN(start_time) AS start_time, MAX(end_time) AS end_time").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Group("program_round,event_id").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("GetPage error:%s \r\n", err)
		return err
	}

	return nil
}

func (e *MonitorEvent) GetProgramByRound(c *dto.GetProgramByRoundReq) ([]monitor.ProgramRound, error) {
	rounds := make([]monitor.ProgramRound, 0, 5)
	err := e.Orm.Model(&monitor.ProgramRound{}).Where("event_id=? and program_round in ?", c.EventId, c.Rounds).Find(&rounds).Error
	if err != nil {
		e.Log.Errorf("GetProgramByRound error:%s \r\n", err)
		return rounds, err
	}

	return rounds, nil
}

func (e *MonitorEvent) SaveEventMember(c *dto.SaveEventMemberReq) error {
	now := time.Now().Unix()
	for k, _ := range c.EventMembers {
		rand.Seed(time.Now().UnixNano())
		// 生成随机的6位数字
		randomNumber := rand.Intn(900000) + 100000
		*(&c.EventMembers[k].InvitationCode) = strconv.Itoa(randomNumber)
		*(&c.EventMembers[k].CreateTime) = now
		*(&c.EventMembers[k].UpdateTime) = now
	}
	err := e.Orm.Model(&monitor.EventMember{}).Save(&c.EventMembers).Error
	if err != nil {
		e.Log.Errorf("SaveEventMember error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) GetEventMember(c *dto.GetEventMemberReq, count *int64) ([]monitor.EventMemberModel, error) {

	members := make([]monitor.EventMemberModel, 0, 5)
	err := e.Orm.Model(&monitor.EventMember{}).
		Scopes(
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Select("event_member.id,event_member.event_id,event_member.member_id,worksite_member.member_name,worksite_member.member_account,worksite.worksite,event_member.invitation_code").
		Joins(" left join worksite_member on worksite_member.id = event_member.member_id").
		Joins(" left join worksite on worksite.id = worksite_member.worksite_id").
		Where("event_member.event_id=?", c.EventId).Find(&members).
		Limit(-1).Offset(-1).
		Count(count).
		Error
	if err != nil {
		e.Log.Errorf("GetEventMember error:%s \r\n", err)
		return members, err
	}
	return members, nil
}

func (e *MonitorEvent) GetBindEventMember(c *dto.GetEventMemberReq) ([]int, error) {

	ids := make([]int, 0, 5)

	err := e.Orm.Model(&monitor.EventMember{}).Select("member_id").Where("event_id=?", c.EventId).Find(&ids).Error
	if err != nil {
		e.Log.Errorf("GetEventMember error:%s \r\n", err)
		return ids, err
	}
	return ids, nil
}

func (e *MonitorEvent) DeleteEventMember(c *dto.DeleteEventMemberReq) error {

	err := e.Orm.Model(&monitor.EventMember{}).Where("id=?", c.Id).Delete(&monitor.EventMember{}).Error
	if err != nil {
		e.Log.Errorf("DeleteEventMember error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *MonitorEvent) GetMemberByCode(d *dto.GetMemberByCodeReq) (monitor.MemberInfo, error) {
	info := monitor.MemberInfo{}

	event := monitor.MonitorEvent{}
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("task_state =1").Find(&event).Error
	if err != nil {
		e.Log.Errorf("获取活动事件:%s \r\n", err)
		return info, err
	}

	eventMember := monitor.EventMember{}

	err = e.Orm.Model(&monitor.EventMember{}).Where("tenant_id = ? and invitation_code=? and event_id = ?", d.TenantId, d.Code, event.Id).Find(&eventMember).Error
	if err != nil {
		e.Log.Errorf("获取成员通过邀请码:%s \r\n", err)
		return info, err
	}
	if eventMember.Id <= 0 {
		return info, errors.New(string(apis.WorksiteMemberError.Code))
	}

	member := monitor.WorksiteMember{}
	err = e.Orm.Model(&monitor.WorksiteMember{}).Where("id = ? ", eventMember.MemberId).Find(&member).Error
	if err != nil {
		e.Log.Errorf("获取成员:%s \r\n", err)
		return info, err
	}
	info.WorksiteMember = member

	worksite := monitor.Worksite{}
	err = e.Orm.Model(&monitor.Worksite{}).Where("id = ? ", member.WorkSiteId).Find(&worksite).Error
	if err != nil {
		e.Log.Errorf("获取工口:%s \r\n", err)
		return info, err
	}
	info.Worksite = worksite

	eventId := strconv.Itoa(eventMember.EventId)
	monitorBasics := make([]monitor.MonitorBasic, 0, 5)
	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("bind_id=?", eventId).Find(&monitorBasics).Error
	if err != nil {
		e.Log.Errorf("获取监看地址失败:%s ", err)
		return info, err
	}

	basicIds := make([]int, 0, 5)
	for _, basic := range monitorBasics {
		basicIds = append(basicIds, basic.Id)
	}

	monitorConfigs := make([]monitor.MonitorConfig, 0, 5)
	err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id in ?", basicIds).Find(&monitorConfigs).Error
	if err != nil {
		e.Log.Errorf("获取监看地址失败:%s ", err)
		return info, err
	}
	models := make([]monitor.MonitorModel, 0, 5)
	for _, basic := range monitorBasics {
		model := monitor.MonitorModel{}
		basic := basic
		model.MonitorBasic = basic
		worksites := strings.Split(basic.Worksites, ",")

		for _, worksite := range worksites {
			memberWorksite := strconv.Itoa(member.WorkSiteId)
			if memberWorksite == worksite {
				models = append(models, model)
				break
			}
		}
	}
	for k, model := range models {
		configs := make([]monitor.MonitorConfig, 0, 3)
		for _, config := range monitorConfigs {
			config := config
			if config.BasicId == int64(model.MonitorBasic.Id) {
				configs = append(configs, config)
			}
		}
		*(&models[k].MonitorConfigs) = configs
	}
	info.MonitorModels = models

	monitorEvent := monitor.MonitorEvent{}
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id = ? ", eventMember.EventId).Find(&monitorEvent).Error
	if err != nil {
		e.Log.Errorf("获取活动失败:%s \r\n", err)
		return info, err
	}
	info.MonitorEvent = monitorEvent

	return info, nil
}

func (e *MonitorEvent) CopyEventMonitor(d *dto.CopyMonitorEventReq) error {

	event := monitor.MonitorEvent{}
	err := e.Orm.Model(&monitor.MonitorEvent{}).Where("id = ?", d.Id).Find(&event).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent error:%s ", err)
		return err
	}

	now := time.Now()
	//复制活动
	event.Id = 0
	event.TaskState = 0
	req := &dto.MonitorEventInsertReq{
		Id:        0,
		TenantId:  event.TenantId,
		EventName: event.EventName + "副本",
		SetId:     event.SetId,
	}
	err = e.Insert(req)
	if err != nil {
		e.Log.Errorf("insert MonitorEvent error:%s ", err)
		return err
	}

	newEvent := monitor.MonitorEvent{}
	err = e.Orm.Model(&monitor.MonitorEvent{}).Where("id=?", req.Id).Find(&newEvent).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent error:%s ", err)
		return err
	}

	//复制监看
	event.Id = req.Id
	monitorBasics := make([]monitor.MonitorBasic, 0, 5)
	bindId := strconv.Itoa(d.Id)
	err = e.Orm.Model(&monitor.MonitorBasic{}).Where("bind_id = ?", bindId).Find(&monitorBasics).Error
	if err != nil {
		e.Log.Errorf("get MonitorEvent error:%s ", err)
		return err
	}

	for _, monitorBasic := range monitorBasics {
		basicId := monitorBasic.Id
		monitorBasic := monitorBasic
		monitorBasic.Id = 0
		monitorBasic.MonitorState = 2
		monitorBasic.BindId = strconv.Itoa(event.Id)

		err = e.Orm.Model(&monitor.MonitorBasic{}).Create(&monitorBasic).Error
		if err != nil {
			e.Log.Errorf("Create monitorBasic error:%s ", err)
			return err
		}
		configs := make([]monitor.MonitorConfig, 0, 5)
		err = e.Orm.Model(&monitor.MonitorConfig{}).Where("basic_id = ?", basicId).Find(&configs).Error
		if err != nil {
			e.Log.Errorf("get MonitorConfig error:%s ", err)
			return err
		}
		for k, _ := range configs {
			*(&configs[k].Id) = 0
			*(&configs[k].BasicId) = int64(monitorBasic.Id)
		}
		if len(configs) > 0 {
			err = e.Orm.Model(&monitor.MonitorConfig{}).Create(&configs).Error
			if err != nil {
				e.Log.Errorf("Create MonitorConfig error:%s ", err)
				return err
			}
		}
	}

	//复制活动成员
	eventMembers := make([]monitor.EventMember, 0, 5)
	err = e.Orm.Model(&monitor.EventMember{}).Where("event_id = ?", d.Id).Find(&eventMembers).Error
	if err != nil {
		e.Log.Errorf("get EventMember error:%s ", err)
		return err
	}
	for k, _ := range eventMembers {
		*(&eventMembers[k].Id) = 0
		*(&eventMembers[k].EventId) = event.Id
	}

	if len(eventMembers) > 0 {
		err = e.Orm.Model(&monitor.EventMember{}).Create(&eventMembers).Error
		if err != nil {
			e.Log.Errorf("Create EventMember error:%s ", err)
			return err
		}
	}

	//复制节目单
	res, err := e.GetProgram(&vrpmDto.GetProgramReq{ChannelId: event.ChannelId, VersionId: event.VersionId, StartTime: int(now.AddDate(0, 0, -3).Unix()), EndTime: int(now.AddDate(0, 0, 3).Unix())})
	if err != nil {
		e.Log.Errorf("GetProgram error:%s ", err)
		return err
	}

	tempEpgs := make([]vrpmDto.Epg, 0, 5)
	if len(res) > 0 {
		for _, epgRes := range res {
			for _, re := range epgRes {
				epg := vrpmDto.Epg{}
				epg.EventId = newEvent.Id
				epg.ProgramId = re.ProgramId
				epg.ChannelId = newEvent.ChannelId
				epg.TenantId = newEvent.TenantId
				epg.StartTime = re.StartTime
				epg.EndTime = re.EndTime
				epg.DelaySecond = re.DelaySecond
				epg.DelayType = re.DelayType
				epg.Describe = re.Describe
				epg.ProgramName = re.ProgramName
				epg.Language = re.Language
				epg.IsSkip = re.IsSkip
				epg.CreateTime = now.Unix()
				epg.UpdateTime = now.Unix()
				tempEpgs = append(tempEpgs, epg)
			}

		}
		errorCode, err := e.SaveProgram(&vrpmDto.SaveProgramReq{ChannelId: newEvent.ChannelId, Epgs: tempEpgs, VersionId: newEvent.VersionId, EventId: event.Id})
		if err != nil {
			e.Log.Errorf("SaveProgram error:%s ", err)
			return errors.New(string(errorCode))
		}
	}

	//复制工口消息
	notices := make([]monitor.WorksiteNotice, 0, 5)
	err = e.Orm.Model(&monitor.WorksiteNotice{}).Where("event_id=?", d.Id).Find(&notices).Error
	if err != nil {
		e.Log.Errorf("get WorksiteNotice error:%s ", err)
		return err
	}

	for k, _ := range notices {
		*(&notices[k].EventId) = newEvent.Id
		*(&notices[k].Id) = 0
	}

	if len(notices) > 0 {
		err = e.Orm.Model(&monitor.WorksiteNotice{}).Create(&notices).Error
		if err != nil {
			e.Log.Errorf("create WorksiteNotice error:%s ", err)
			return err
		}
	}

	return nil
}
